package com.uinnova.product.eam.service.es;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uinnova.product.eam.comm.model.es.CEamResource;
import com.uinnova.product.eam.comm.model.es.EamResource;
import com.uino.dao.AbstractESBaseDao;
import com.uino.service.util.FileUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * EAM 资源文件
 * @author Shaolong.fan
 */
@Service
public class IamsEamESResourceDao extends AbstractESBaseDao<EamResource, CEamResource> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @PostConstruct
    public void init(){
        List<EamResource> list = FileUtil.getData("/initdata/uino_eam_resource.json", EamResource.class);
        super.initIndex(list);
    }

    @Override
    public String getIndex() {
        return "uino_eam_resource";
    }

    @Override
    public String getType() {
        return getIndex();
    }

    public List<EamResource> selectByHighLight(QueryBuilder queryBuilder, List<SortBuilder<?>> sorts, int limit) {
        //1，构建SearchRequest请求对象，指定索引库
        SearchRequest searchRequest = new SearchRequest(getIndex());
        //2,构建SearchSourceBuilder查询对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(1);
        sourceBuilder.size(limit);
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<b>");
        highlightBuilder.postTags("</b>");
        highlightBuilder.highlighterType("plain");
        highlightBuilder.field("name").field("operator");
        sourceBuilder.highlighter(highlightBuilder);
        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);
        if(!CollectionUtils.isEmpty(sorts)){
            sorts.forEach(sort -> sourceBuilder.sort(sort));
        }
        try {
            //6,调用方法查询数据
            SearchResponse searchResponse = getClient().search(searchRequest, RequestOptions.DEFAULT);
            //7,解析返回结果
            SearchHit[] hits = searchResponse.getHits().getHits();
            if(hits.length == 0){
                return Collections.emptyList();
            }
            List<EamResource> resources = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                Map<String, Object> map = hit.getSourceAsMap();
                logger.info("返回的结果:{}" , hit.getSourceAsString());
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if(!CollectionUtils.isEmpty(highlightFields)){
                    highlightFields.forEach((field, content) -> {
                        StringBuilder ln = new StringBuilder();
                        Text[] fragments = content.getFragments();
                        for (Text fragment : fragments) {
                            ln.append(fragment.string());
                        }
                        map.put(field, ln.toString());
                    });
                }
                String recordStr = JSON.toJSONString(map);
                resources.add(JSONObject.parseObject(recordStr, EamResource.class));
            }
            return resources;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

}
